package org.deng.learn.netty.httpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * @author 邓力宾
 * @Desc
 * @since 2020/6/16 下午12:05
 */
public class HttpServer {

    public void start(int port){
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.channel(NioServerSocketChannel.class);
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        bootstrap.group(boss, worker);
        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // request解码 使用netty提供的
                pipeline.addLast("requestDecoder", new HttpRequestDecoder()); // ChannelInboundHandlerAdapter
                pipeline.addLast("httpAggregator", new HttpObjectAggregator(65536)); // 将消息行，消息头，消息体封装为AggregatedFullHttpRequest
                // response编码
                pipeline.addLast("responseEncoder", new HttpResponseEncoder()); //ChannelOutboundHandlerAdapter

                // request处理
                pipeline.addLast("serverHandler", new HttpRequestHandler()); // ChannelInboundHandlerAdapter

            }
        });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("服务已经启动");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.start(8090);
    }
}
